import { Injectable } from "@nestjs/common";
import { UserRepository } from "../repository";
import { QueryHook } from "src/config/types";
import { UserEntity } from "../entity/user.entity";
import { EntityNotFoundError } from "typeorm";
import { CreateUserDto } from "../dto/user.dto";

@Injectable()
export class UserService {
    constructor(
       protected userRepository:UserRepository
    ){}

    async findOneByCredential(credential: string, callback?: QueryHook<UserEntity>){
       let qb=this.userRepository.createQueryBuilder()
       if(callback){
        qb= await callback(qb)
       }

       //跟据传入的凭证 进行登录
    return  await qb.where('user.phone=:credential',{credential})
         .andWhere('user.email=:credential',{credential})
         .andWhere('user.username=:credential',{credential})
         .getOne()
    }

   async findOneByCondition(condition: { [key: string]: any }, callback?: QueryHook<UserEntity>){
        let qb=this.userRepository.createQueryBuilder()
        if(callback){
         qb= await callback(qb)
        }

        //将对象转换成数组（为了安全）
       let wheres= Object.fromEntries(Object.entries(condition).map(([k,v])=>[k,v]))

        //跟据条件进行查询
       let user= qb.where(wheres).getOne()
        if (!user) {
            throw new EntityNotFoundError(UserEntity, Object.keys(condition).join(','));
        }
        return user;
    }
    async create(data: CreateUserDto) {
       this.userRepository.createQueryBuilder()
                          .insert()
                          .values({
                            ...data
                          })
                          .execute()
      
    }


}